# 该脚本文件需要修改第10行（classes）即可
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
from tqdm import tqdm
import os
from os import getcwd

sets = ['train', 'test', 'val']
# 这里使用要改成自己的类别
classes = ['drone']

# 配置文件路径
config = {
    'annotations_dir': r'E:\pycharmProjs\yolo-ladcs\dataset\VOCdevkit-TIB\VOC2007\Annotations',
    'imagesets_dir': r'E:\pycharmProjs\yolo-ladcs\dataset\VOCdevkit-TIB\VOC2007\ImageSets\Main',
    'jpegimages_dir': r'E:\pycharmProjs\yolo-ladcs\dataset\VOCdevkit-TIB\VOC2007\JPEGImages',
    'labels_dir': r'E:\pycharmProjs\yolo-ladcs\dataset\TIB-NET-YOLO\mixed_labels',
    'YOLO-ROOT': r'E:\pycharmProjs\yolo-ladcs\dataset\TIB-NET-YOLO'
}

def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = (box[0] + box[1]) / 2.0 - 1
    y = (box[2] + box[3]) / 2.0 - 1
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    x = round(x, 6)
    w = round(w, 6)
    y = round(y, 6)
    h = round(h, 6)
    return x, y, w, h


def convert_annotation(image_id):
    try:
        # 打开xml标注文件和YOLO标注文件
        with open(fr"{config['annotations_dir']}\TIB-{image_id}.xml", encoding='utf-8') as in_file, \
                open(fr"{config['labels_dir']}\TIB-{image_id}.txt", 'w', encoding='utf-8') as out_file:
            tree = ET.parse(in_file)
            root = tree.getroot()
            size = root.find('size')
            w = int(size.find('width').text)
            h = int(size.find('height').text)
            for obj in root.iter('object'):
                difficult = obj.find('difficult').text
                cls = obj.find('name').text.lower()  # 转换为小写
                if cls not in classes or int(difficult) == 1:
                    continue
                cls_id = classes.index(cls)
                xmlbox = obj.find('bndbox')
                b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
                     float(xmlbox.find('ymax').text))
                b1, b2, b3, b4 = b
                # 标注越界修正
                if b2 > w:
                    b2 = w
                if b4 > h:
                    b4 = h
                b = (b1, b2, b3, b4)
                bb = convert((w, h), b)
                out_file.write(f"{cls_id} {' '.join([str(a) for a in bb])}\n")
    except Exception as e:
        print(f"Error processing {image_id}: {e}")


if __name__ == '__main__':
    wd = getcwd()
    for image_set in sets:
        if not os.path.exists(config['labels_dir']):
            os.makedirs(config['labels_dir'])
        with open(fr"{config['imagesets_dir']}\{image_set}.txt", 'r', encoding='utf-8') as image_ids_file:
            image_ids = image_ids_file.read().strip().split()
        # 生成train/val/test列表文件
        with open(fr"{config['YOLO-ROOT']}\{image_set}.txt", 'w', encoding='utf-8') as list_file:
            for image_id in tqdm(image_ids):
                list_file.write(fr"{config['jpegimages_dir']}\TIB-{image_id}.jpg" + '\n')
                convert_annotation(image_id)
